package edu.hawaii.duedates;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * A class for the Hawaii State Public Library System.
 * 
 * @author Arthur Shum and Erin Kim.
 */
public class HawaiiStateLibrary implements Library {

  /** The URL to log in to the Hawaii State Public Library System. */
  private static final String url = "http://www.librarieshawaii.org/";

  /** The patron's library card barcode number. Used to log in to the library system. */
  private final String barcode;
  // 0011429495

  /** The last 4 digits of the patron's phone number. Used to log in to the library system. */
  private final String pin;
  // 3845

  /**
   * Constructs a HawaiiStateLibrary object, given a patron's library barcode number and the last 4
   * digits of their phone number.
   * 
   * @param barcode The patron's library card barcode number.
   * @param pin The last 4 digits of the patron's phone number.
   */
  public HawaiiStateLibrary(String barcode, String pin) {
    this.barcode = barcode;
    this.pin = pin;
  }

  /**
   * Attempts to log in to the Hawaii State Public Library System.
   * 
   * @return The WebConversation after logging in.
   * @throws Exception If an errors occurs while logging in.
   */
  public WebConversation login() throws Exception {
    try {
      // Website has bogus JavaScript code.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(url);
      WebResponse response = conversation.getResponse(request);
      WebLink link = response.getLinkWith("My Account");
      link.click();
      response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      form.setParameter("sec1", this.barcode);
      form.setParameter("sec2", this.pin);
      form.submit();
      return conversation;
    }
    catch (Exception e) {
      throw new Exception("Error while logging in to Hawaii State Public Library System", e);
    }
  }

  /**
   * Retrieves information about items checked out from the Hawaii State Library by the logged-in
   * patron. The information is stored in a table where the text of cell 0,0 is "Title".
   * 
   * @return A ready-to-print string containing info about checked-out items.
   * @throws Exception If an error occurs while retrieving info.
   */
  public String getInfo() throws Exception {
    try {
      WebConversation conversation = this.login();
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      WebTable table = response.getTableStartingWith("Title");
      // If the table containing the information doesn't exist.
      if (table == null) {
        return "\nNo items checked out from the Hawaii State Public Library System.\n\n";
      }
      else {
        return formatInfo(table);
      }
      /*
       * boolean noBooksOut = response.getText().contains("Checked Out: 0"); 
       * if (noBooksOut) {
       *   return "No items checked out from the Hawaii State Library."; 
       * } 
       * else { 
       *   WebTable table = response.getTableStartingWith("Title"); return formatInfo(table); 
       * }
       */
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Public Library System info", e);
    }
  }

  /**
   * Formats information stored in a table into a ready-to-print string. In the table, each row is
   * for a separate item; column 0 is for the title and author; column 1 is for the checkout date;
   * and column 2 is for the due date.
   * 
   * @param table The WebTable containing checked-out item info.
   * @return A ready-to-print string containing info about checked-out items.
   */
  private String formatInfo(WebTable table) {
    String items = "\nResults for the Hawaii State Public Library System:\n\n";
    for (int i = 1; i < table.getRowCount(); i++) {
      String titleAuthor = table.getCellAsText(i, 0);
      // Find where the title ends and where the author begins.
      int titleEnd = titleAuthor.indexOf(" /\n");
      int authorBegin = titleAuthor.indexOf("by ", titleEnd) + 3;
      // Skip first 2 characters: "| "
      String title = titleAuthor.substring(2, titleEnd);
      String author = titleAuthor.substring(authorBegin);
      String outDate = table.getCellAsText(i, 1);
      String dueDate = table.getCellAsText(i, 2);
      items = items.concat("Title   :  " + title + "\n");
      items = items.concat("Author  :  " + author + "\n");
      items = items.concat("Out Date:  " + outDate + "\n");
      items = items.concat("Due Date:  " + dueDate + "\n\n");
    }
    return items;
  }

}
